using System;
using CUE4Parse.Encryption.Aes;
using CUE4Parse.UE4.VirtualFileSystem;

namespace CUE4Parse.GameTypes.UDWN.Encryption.Aes;

/// <summary>
/// Reversed by Spiritovod
/// </summary>
public static class ToaaAes
{
    private static readonly byte[] expand =
    [
        0x27, 0x1A, 0x0D, 0x00, 0x5B, 0x4E, 0x41, 0x34, 0x8F, 0x82, 0x75, 0x68, 0xC3, 0xB6, 0xA9, 0x9C,
        0xF7, 0xEA, 0xDD, 0xD0, 0x2B, 0x1E, 0x11, 0x04, 0x5F, 0x52, 0x45, 0x38, 0x93, 0x86, 0x79, 0x6C,
        0xC7, 0xBA, 0xAD, 0xA0, 0xFB, 0xEE, 0xE1, 0xD4, 0x2F, 0x22, 0x15, 0x08, 0x63, 0x56, 0x49, 0x3C,
        0x97, 0x8A, 0x7D, 0x70, 0xCB, 0xBE, 0xB1, 0xA4, 0xFF, 0xF2, 0xE5, 0xD8, 0x33, 0x26, 0x19, 0x0C,
        0x67, 0x5A, 0x4D, 0x40, 0x9B, 0x8E, 0x81, 0x74, 0xCF, 0xC2, 0xB5, 0xA8, 0x03, 0xF6, 0xE9, 0xDC,
        0x37, 0x2A, 0x1D, 0x10, 0x6B, 0x5E, 0x51, 0x44, 0x9F, 0x92, 0x85, 0x78, 0xD3, 0xC6, 0xB9, 0xAC,
        0x07, 0xFA, 0xED, 0xE0, 0x3B, 0x2E, 0x21, 0x14, 0x6F, 0x62, 0x55, 0x48, 0xA3, 0x96, 0x89, 0x7C,
        0xD7, 0xCA, 0xBD, 0xB0, 0x0B, 0xFE, 0xF1, 0xE4, 0x3F, 0x32, 0x25, 0x18, 0x73, 0x66, 0x59, 0x4C
    ];

    private static readonly byte[] convert =
    [
        0x60, 0xDA, 0x4A, 0xC9, 0x4D, 0xA7, 0x28, 0x41, 0xF2, 0x6F, 0xDC, 0x5B, 0x17, 0x54, 0x09, 0x2C,
        0xA8, 0x2B, 0xAD, 0x31, 0x0D, 0xE0, 0xBB, 0x37, 0x6C, 0x24, 0xA3, 0x0F, 0x75, 0x45, 0x18, 0xEF,
        0xEA, 0x7F, 0x06, 0x58, 0xFE, 0x88, 0xBC, 0xB7, 0x4B, 0xE5, 0x83, 0x2F, 0xA0, 0x32, 0xCE, 0x5D,
        0xD7, 0x5A, 0xD5, 0x9A, 0x3F, 0x80, 0x81, 0xAE, 0x6B, 0x50, 0xED, 0x4F, 0x8B, 0x72, 0x56, 0xBE,
        0xEB, 0x8F, 0x68, 0x4C, 0x6E, 0x01, 0x99, 0x89, 0xD0, 0x14, 0xF8, 0xE2, 0x1C, 0x53, 0x27, 0x66,
        0x25, 0xB1, 0x8E, 0x19, 0x48, 0xD3, 0x9F, 0x84, 0x97, 0xE1, 0x64, 0x10, 0x6A, 0x5C, 0x42, 0x2A,
        0xCB, 0x3B, 0x65, 0xBF, 0xB6, 0x52, 0x2E, 0x55, 0xF4, 0x62, 0x44, 0xA9, 0xBD, 0x95, 0x61, 0xB8,
        0x5F, 0xC0, 0x23, 0x78, 0x8D, 0x91, 0xB0, 0xA1, 0xC4, 0x08, 0xAB, 0x79, 0xE6, 0xC8, 0xB4, 0x85,
        0x82, 0x20, 0x0B, 0xDB, 0xC2, 0x8C, 0xD8, 0x51, 0x15, 0x11, 0xEE, 0x63, 0xB2, 0x1B, 0xDE, 0x7B,
        0xFC, 0x2D, 0xA4, 0x5E, 0xF3, 0x90, 0x46, 0x59, 0xF6, 0xD1, 0x35, 0x33, 0x7C, 0x40, 0xA5, 0x73,
        0xB3, 0x1D, 0x92, 0x0C, 0x1F, 0x29, 0xF0, 0x49, 0x39, 0x16, 0xD2, 0xE4, 0x9C, 0x13, 0x34, 0x21,
        0x71, 0xD6, 0xE3, 0xF9, 0x69, 0xFF, 0xAA, 0xB9, 0xC3, 0xAF, 0x00, 0xA6, 0x3A, 0x9E, 0x07, 0x77,
        0x1E, 0x9D, 0x87, 0xC1, 0x05, 0xC7, 0x57, 0xCD, 0x30, 0x6D, 0xFB, 0x74, 0x86, 0x96, 0xBA, 0xDD,
        0xC5, 0x04, 0xF1, 0xAC, 0x02, 0xCA, 0xC6, 0x4E, 0x36, 0x47, 0x8A, 0xFA, 0x98, 0x7D, 0x1A, 0xD9,
        0x12, 0xF5, 0x94, 0x0E, 0xD4, 0x7A, 0xE9, 0xF7, 0x76, 0x7E, 0x03, 0xA2, 0xDF, 0xE7, 0xCC, 0x67,
        0xB5, 0xFD, 0x3C, 0x22, 0x38, 0x9B, 0x43, 0x26, 0x0A, 0x93, 0xEC, 0x3E, 0x3D, 0xE8, 0x70, 0xCF
    ];

    private static uint GETU32(ReadOnlySpan<byte> plaintext) => (uint) (plaintext[0] << 24 | plaintext[1] << 16 | plaintext[2] << 8 | plaintext[3]);

    private static void PUTU32(Span<byte> ciphertext, uint st)
    {
        ciphertext[0] = (byte) (st >> 24);
        ciphertext[1] = (byte) (st >> 16);
        ciphertext[2] = (byte) (st >> 8);
        ciphertext[3] = (byte) st;
    }

    private static uint ROL4(uint v, uint n)
    {
        n &= 31;
        return n != 0 ? (v << (int) n) | (v >> (int) (32 - n)) : 0;
    }

    private static uint ROR4(uint v, uint n)
    {
        n &= 31;
        return n != 0 ? (v >> (int) n) | (v << (int) (32 - n)) : 0;
    }

    private static void ExpandKey(ReadOnlySpan<byte> key, Span<uint> rk)
    {
        Span<uint> internalKey = stackalloc uint[4];

        internalKey[0] = GETU32(key) ^ 0xB9B7ED68;
        internalKey[1] = GETU32(key[4..]) ^ 0x71750A9F;
        internalKey[2] = GETU32(key[8..]) ^ 0xA6070525;
        internalKey[3] = GETU32(key[12..]) ^ 0x3AA8C2C5;

        for (var i = 0; i < 32; i++)
        {
            var tmpExpand = BitConverter.ToUInt32(expand, i * 4);
            var tempInt = tmpExpand ^ internalKey[(i + 1) % 4] ^ internalKey[(i + 2) % 4] ^ internalKey[(i + 3) % 4];
            Span<byte> temp = BitConverter.GetBytes(tempInt);
            var tablePart01 = convert[temp[0]] | (uint)(convert[temp[1]] << 8);
            var tablePart012 = tablePart01 | (uint)(convert[temp[2]] << 16);
            var tableEntry = tablePart012 | (uint)(convert[temp[3]] << 24);
            var rkValue = tableEntry ^ internalKey[i % 4] ^ ROR4(tableEntry, 9) ^ ROL4(tableEntry, 13);
            internalKey[i % 4] = rkValue;
            rk[i] = rkValue;
        }
    }

    private static void Decrypt16(Span<uint> rk, Span<byte> input, Span<byte> output)
    {
        var internalData = new uint[4];

        internalData[0] = GETU32(input);
        internalData[1] = GETU32(input[4..]);
        internalData[2] = GETU32(input[8..]);
        internalData[3] = GETU32(input[12..]);

        for (var i = 0; i < 32; i++)
        {
            var tempInt = rk[31 - i] ^ internalData[(i + 1) % 4] ^ internalData[(i + 2) % 4] ^ internalData[(i + 3) % 4];
            var temp = BitConverter.GetBytes(tempInt);
            var tablePart0 = convert[temp[0]];
            var tablePart01 = tablePart0 | (uint)(convert[temp[1]] << 8);
            var tablePart012 = tablePart01 | (uint)(convert[temp[2]] << 16);
            var tableEntry = tablePart012 | (uint)(convert[temp[3]] << 24);
            internalData[i % 4] ^= tableEntry ^ ROL4(tableEntry, 2) ^ ROR4(tableEntry, 8) ^ ROL4(tableEntry, 10) ^ ROR4(tableEntry, 14);
        }

        PUTU32(output, internalData[3]);
        PUTU32(output[4..], internalData[2]);
        PUTU32(output[8..], internalData[1]);
        PUTU32(output[12..], internalData[0]);
    }

    public static byte[] ToaaDecrypt(byte[] bytes, int beginOffset, int count, bool isIndex, IAesVfsReader reader)
    {
        if (bytes.Length < beginOffset + count)
            throw new IndexOutOfRangeException("beginOffset + count is larger than the length of bytes");
        if (count % 16 != 0)
            throw new ArgumentException("count must be a multiple of 16");
        if (reader.AesKey == null)
            throw new NullReferenceException("reader.AesKey");

        var key = reader.AesKey.Key;
        Span<uint> rk = stackalloc uint[32];
        ExpandKey(key, rk);

        var paddedLength = 16 * ((count + 15) / 16);
        var tempEncrypted = new byte[paddedLength];
        Array.Copy(bytes, beginOffset, tempEncrypted, 0, count);

        var tempDecrypted = new byte[paddedLength];
        for (var i = 0; i < paddedLength / 16; i++)
        {
            Decrypt16(rk, tempEncrypted.AsSpan(i * 16, 16), tempDecrypted.AsSpan(i * 16, 16));
        }

        var output = new byte[count];
        Array.Copy(tempDecrypted, 0, output, 0, count);

        return output;
    }
}
